//
//  DZNetworkBase.m
//  DZToolbox
//
//  Created by Darren on 15/5/12.
//  Copyright (c) 2015年 Darren Zheng. All rights reserved.
//

#import "DZNetworkBase.h"

@interface DZNetworkBase ()

@end

@implementation DZNetworkBase

#pragma mark - 核心请求方法 -

- (void)getWithURLString:(NSString *)strURL
                  params:(NSMutableDictionary *)mDictParams
                 success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))blockSuccess
                 failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))blockFailure
{
    NSString *strFullURL = [self strURLHeader] ? [[self strURLHeader] stringByAppendingString:strURL] : strURL;
    
    AFHTTPRequestOperationManager *manager = [self setupManager];
    manager.requestSerializer.timeoutInterval = [self fTimeoutSec];
    NSLog(@"【%@ - Request Start】%@",strURL, strFullURL);
    NSLog(@"【%@ - Params】%@",strURL, mDictParams);
    [manager GET:strFullURL parameters:mDictParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self successWithOperation:operation
                    responseObject:responseObject
                            strURL:strURL
                           success:blockSuccess
                           failure:blockFailure];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self failureWithOperation:operation
                            strURL:strURL
                             error:error
                           failure:blockFailure];
    }];
}

- (void)getImageWithURLString:(NSString *)strURL
                       params:(NSMutableDictionary *)mDictParams
                      success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))blockSuccess
                      failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))blockFailure
{
    NSString *strFullURL = [self strURLHeader] ? [[self strURLHeader] stringByAppendingString:strURL] : strURL;
    AFHTTPRequestOperationManager *manager = [self setupManager];
    manager.requestSerializer.timeoutInterval = [self fTimeoutSec];
    NSLog(@"【%@ - Request Start】%@",strURL, strFullURL);
    NSLog(@"【%@ - Params】%@",strURL, mDictParams);
    
    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:strFullURL]]];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self successWithOperation:operation
                    responseObject:responseObject
                            strURL:strURL
                           success:blockSuccess
                           failure:blockFailure];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self failureWithOperation:operation
                            strURL:strURL
                             error:error
                           failure:blockFailure];
    }];
    [requestOperation start];
}


- (void)postWithURLString:(NSString *)strURL
                   params:(NSMutableDictionary *)mDictParams
                  success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))blockSuccess
                  failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))blockFailure
{
    NSString *strFullURL = [self strURLHeader] ? [[self strURLHeader] stringByAppendingString:strURL] : strURL;
    AFHTTPRequestOperationManager *manager = [self setupManager];
    manager.requestSerializer.timeoutInterval = [self fTimeoutSec];
    NSLog(@"----%@",strFullURL);

    NSLog(@"////%@", mDictParams);
    
    [manager POST:strFullURL parameters:mDictParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self successWithOperation:operation
                    responseObject:responseObject
                            strURL:strURL
                           success:blockSuccess
                           failure:blockFailure];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self failureWithOperation:operation
                            strURL:strURL
                             error:error
                           failure:blockFailure];
    }];
}

- (void)uploadWithURLString:(NSString *)strURL
                     params:(NSMutableDictionary *)mDictParams
                     images:(NSArray *)arrayImages
                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))blockSuccess
                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))blockFailure
{
    AFHTTPRequestOperationManager *manager = [self setupManager];
    manager.requestSerializer.timeoutInterval = [self fTimeoutSec];
    // 拼接要发送的data，设置图片压缩率
    NSMutableArray *mArrayImageDatas = [NSMutableArray new];
    for (UIImage *image in arrayImages)
    {
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [mArrayImageDatas addObject:imageData];
    }
    /////////////////////////////////////////////////////////////////////
    NSString *strFullURL = [self strURLHeader] ? [[self strURLHeader] stringByAppendingString:strURL] : strURL;
    NSLog(@"【Request Start】%@", strFullURL);
    NSLog(@"【Params】%@", mDictParams);
    [manager POST:strFullURL parameters:mDictParams constructingBodyWithBlock:^(id <AFMultipartFormData> formData)
     {
         for (int i = 0; i < mArrayImageDatas.count; i++)
         {
             [formData appendPartWithFileData:mArrayImageDatas[i]
                                         name:@"file"
                                     fileName:[NSString stringWithFormat:@"image%d.jpeg", i]
                                     mimeType:@"image/jpeg"];
         }
     } success:^(AFHTTPRequestOperation *operation, id responseObject){
         [self successWithOperation:operation
                     responseObject:responseObject
                             strURL:strURL
                            success:blockSuccess
                            failure:blockFailure];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [self failureWithOperation:operation
                             strURL:strURL
                              error:error
                            failure:blockFailure];
     }];
}

- (void)downloadWithURLString:(NSString *)strURL
                       params:(NSMutableDictionary *)mDictParams
                      success:(void (^)(AFHTTPRequestOperation *operation, id responseObject, NSString *strFilePath))blockSuccess
                      failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))blockFailure
                     progress:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))blockProgress
{
    NSString *strFullURL = [self strURLHeader] ? [[self strURLHeader] stringByAppendingString:strURL] : strURL;
    AFHTTPRequestOperationManager *manager = [self setupManager];
    manager.requestSerializer.timeoutInterval = [self fTimeoutSec];
    
    NSLog(@"【Request Start】%@", strFullURL);
    NSLog(@"【Params】%@", mDictParams);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strFullURL]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"database.zip"];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
         [self successWithOperation:operation
                     responseObject:responseObject
                             strURL:strURL
                            success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                blockSuccess(operation, responseObject, path);
                            }
                            failure:blockFailure];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [self failureWithOperation:operation
                             strURL:strURL
                              error:error
                            failure:blockFailure];
     }];
    [operation setDownloadProgressBlock:blockProgress];
    [operation start];
}

#pragma mark - 子类overwrite -

- (NSString *)strURLHeader
{
    return nil;
}

- (NSString *)strSuccessKey
{
    return nil;
}

- (NSString *)strSuccessValue
{
    return nil;
}

- (NSString *)strContentType
{
    return @"text/html";
}

- (NSDictionary *)dictHeader
{
    return nil;
}

- (NSString *)strErrorMessageKey
{
    return nil;
}

- (float)fTimeoutSec
{
    return 30;
}


#pragma mark - 抽象方法 -

- (AFHTTPRequestOperationManager *)setupManager
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // Content-Type
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:[self strContentType]];
    
    // HTTP Header
    if ([self dictHeader]) {
        NSDictionary *dict = [self dictHeader];
        for (NSString *strKey in dict) {
            [manager.requestSerializer setValue:dict[strKey] forHTTPHeaderField:strKey];
        }
    }
    
    return manager;
}

- (void)successWithOperation:(AFHTTPRequestOperation *)operation
              responseObject:(id)responseObject
                      strURL:(NSString *)strURL
                     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))blockSuccess
                     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))blockFailure
{
    if (![self strSuccessKey] && ![self strSuccessValue]) {
        NSLog(@"【%@ - JSON】: %@",strURL, responseObject);
        blockSuccess(operation, responseObject);
    }
    if ([self strSuccessKey] && [self strSuccessValue] && [responseObject objectForKey:[self strSuccessKey]] && [responseObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = responseObject;
        if ([dict[[self strSuccessKey]] intValue] == [[self strSuccessValue] intValue]) {
            NSLog(@"【%@ - JSON】: %@",strURL, responseObject);
            blockSuccess(operation, responseObject);
        } else {
            if ([self strErrorMessageKey]) {
                if ([dict objectForKey:[self strErrorMessageKey]]) {
                    NSError *error = [NSError errorWithDomain:@"DZFoundation" code:999 userInfo:@{NSLocalizedDescriptionKey: [dict objectForKey:[self strErrorMessageKey]]}];
                    
                    blockFailure(operation, error);
                }
            }
        }
    }
}

- (void)failureWithOperation:(AFHTTPRequestOperation *)operation
                      strURL:(NSString *)strURL
                       error:(NSError *)error
                     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))blockFailure
{
    NSLog(@"【%@ - Error】: %@",strURL, error);
    blockFailure(operation, error);
}



@end
